package cn.gem.rainbow.cfg.web.filter;

import cn.gem.rainbow.cfg.SystemParam;
import cn.gem.rainbow.cfg.restful.ResultCodeEnum;
import cn.gem.rainbow.cfg.restful.ResultVO;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author lzh
 * @date 2020/9/28 - 17:03
 */
@Slf4j
public class LimitFilter implements Filter {

    @Autowired
    private SystemParam systemParam;

    private static AtomicInteger counter = new AtomicInteger(0);


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("LimitFilter init...");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try {
            Integer maxRequest = Integer.parseInt(systemParam.getLimitMaxRequest());
            int  currentR = counter.incrementAndGet();
            log.info("currentRequest:{}.",counter.get());
            //某一时刻有maxRequest个请求到来时，返回响应系统繁忙
            if ( currentR >= maxRequest) {
                log.info("limitFlow start:{}", Thread.currentThread().getName());
                HttpServletResponse resp = (HttpServletResponse) servletResponse;
                resp.setCharacterEncoding("UTF-8");
                resp.setContentType("application/json;charset=UTF-8");
                PrintWriter print = resp.getWriter();
                log.warn("触发限流");
                ResultVO resultVO = new ResultVO(ResultCodeEnum.BUSY,null);
                print.write(JSONObject.toJSONString(resultVO));
                return;
            }
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            counter.decrementAndGet();
        }

    }

    @Override
    public void destroy() {
        log.info("销毁-限流过滤器");
    }



}
